//
//  UIColor + Interpolate.swift
//  PageNavigator
//
//  Created by 张奇 on 2025/8/14.
//

import UIKit

public extension UIColor {
    
    var pn_red: CGFloat {
        var r: CGFloat = 0
        getRed(&r, green: nil, blue: nil, alpha: nil)
        return r
    }
    var pn_green: CGFloat {
        var g: CGFloat = 0
        getRed(nil, green: &g, blue: nil, alpha: nil)
        return g
    }
    var pn_blue: CGFloat {
        var b: CGFloat = 0
        getRed(nil, green: nil, blue: &b, alpha: nil)
        return b
    }
    var pn_alpha: CGFloat {
        return cgColor.alpha
    }

    func interpolate(to: UIColor, percent: CGFloat) -> UIColor {
        let r = Interpolate.interpolate(from: pn_red, to: to.pn_red, percent: percent)
        let g = Interpolate.interpolate(from: pn_green, to: to.pn_green, percent: percent)
        let b = Interpolate.interpolate(from: pn_blue, to: to.pn_blue, percent: percent)
        let a = Interpolate.interpolate(from: pn_alpha, to: to.pn_alpha, percent: percent)
        return UIColor(red: r, green: g, blue: b, alpha: a)
    }
    
    func interpolateThemeColor(to: UIColor, percent: CGFloat) -> UIColor {
        
        if #available(iOS 13.0, *) {
            return UIColor { [unowned self](traitCollection) -> UIColor in
                let resolvedFrom = self.resolvedColor(with: traitCollection)
                let resolvedTo = to.resolvedColor(with: traitCollection)
                return resolvedFrom.interpolate(to: resolvedTo, percent: percent)
            }
        } else {
            return interpolate(to: to, percent: percent)
        }
    }

}
